package com.sunseen.capacitormachine.modules.parameter.productivetask;


import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sunseen.capacitormachine.commumication.http.HttpUtil;
import com.sunseen.capacitormachine.commumication.http.RestClient;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.databinding.FragmentToBeProduceListBinding;
import com.sunseen.capacitormachine.modules.parameter.bean.BatchBean;
import com.sunseen.capacitormachine.modules.parameter.event.ModifyBatchIdStatusEvent;
import com.sunseen.capacitormachine.modules.parameter.productivetask.adapter.BatchIdAdapter;
import com.sunseen.capacitormachine.modules.parameter.productivetask.event.RefreshListEvent;
import com.sunseen.capacitormachine.modules.parameter.productparameter.modify.ModifyFragment;
import com.sunseen.capacitormachine.modules.parameter.productparameter.ProductParameterFragment;

import java.util.List;

import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @author zest
 */
public class ToBeProduceTaskFragment extends BaseFragment {
    @Override
    protected int setLayout() {
        return R.layout.fragment_to_be_produce_list;
    }


    private BatchIdAdapter adapter;
    private RecyclerView recyclerView;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        EventBus.getDefault().register(this);
        final FragmentToBeProduceListBinding binding = (FragmentToBeProduceListBinding) viewDataBinding;
        recyclerView = binding.rvTask;
        binding.rvTask.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new BatchIdAdapter(R.layout.layout_item_batch);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            ProductParameterFragment fragment = new ProductParameterFragment();
            Bundle bundle = new Bundle();
            BatchBean parameter = (BatchBean) adapter.getData().get(position);
            bundle.putString("batchId", parameter.getBatchId());
            fragment.setArguments(bundle);
            getParent().getParent().start(fragment);
        });
        adapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.img_btn_modify) {
                ModifyFragment modifyFragment = new ModifyFragment();
                Bundle bundle = new Bundle();
                BatchBean parameter = (BatchBean) adapter.getData().get(position);
                bundle.putString("batchId", parameter.getBatchId());
                modifyFragment.setArguments(bundle);
                getParent().getParent().start(modifyFragment);
            }
        });
        adapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                BatchBean batchBean = (BatchBean) adapter.getData().get(position);
                EventBus.getDefault().post(new ModifyBatchIdStatusEvent(batchBean.getBatchId(), 0));
                return false;
            }
        });
        binding.rvTask.setAdapter(adapter);
    }

    private int curPage = 0;

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        adapter.setOnLoadMoreListener(() -> {
                    queryList(curPage + 1, true);
                }
                , recyclerView);
        adapter.disableLoadMoreIfNotFullPage();
        adapter.setEnableLoadMore(true);
        queryList(curPage, true);
    }

    private boolean showNullToast = false;

    /**
     * 请求批次号列表
     *
     * @param page    请求的列表的页码 (每页数据默认10条)
     * @param addLast true:往列表后面添加， false:刷新列表
     */
    private void queryList(int page, boolean addLast) {
        RestClient.builder()
                .url(HttpUtil.Process)
                .params("status", 0)
                .params("page", page)
                .success((String response) -> {
                    JSONObject rootObj = JSON.parseObject(response);
                    if (rootObj != null) {
                        if (rootObj.getIntValue("status") == 1) {
                            JSONObject dataObj = rootObj.getJSONObject("data");
                            if (dataObj != null) {
                                JSONObject listObj = dataObj.getJSONObject("list");
                                if (listObj != null) {
                                    List<BatchBean> list = JSON.parseArray(listObj.getJSONArray("data").toJSONString(), BatchBean.class);
                                    if (list != null) {
                                        if (list.size() > 0) {
                                            curPage = listObj.getIntValue("current_page");
                                            Log.e("test", "list.size = " + list.size());
                                            if (addLast) {
                                                adapter.addData(list);
                                            } else {
                                                adapter.setNewData(list);
                                            }
                                            adapter.loadMoreComplete();
                                        } else {

                                            if (curPage == 0) {
                                                //服务器中无数据
                                                if (showNullToast) {
                                                    Toast.makeText(_mActivity, "后台无相关数据", Toast.LENGTH_SHORT).show();
                                                } else {
                                                    showNullToast = true;
                                                }
                                            } else {
                                                //已加载到最后一页
                                                adapter.setEnableLoadMore(false);
                                            }
                                        }
                                    } else {
                                        Toast.makeText(_mActivity, "请求结果为空: ", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Toast.makeText(_mActivity, "请求结果为空: ", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(_mActivity, "请求结果为空: ", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            String msg = rootObj.getString("message");
                            if (msg == null) {
                                msg = "未知原因";
                            }
                            Toast.makeText(_mActivity, "请求结果为空: " + msg, Toast.LENGTH_SHORT).show();
                            Log.e("test", msg);
                        }
                    } else {
                        Toast.makeText(_mActivity, "请求结果为空", Toast.LENGTH_SHORT).show();
                    }
                })
                .failure(() -> {
                    Log.e("test", "待生产批号列表请求失败");
                    Toast.makeText(_mActivity, "待生产批号列表请求失败", Toast.LENGTH_SHORT).show();
                })
                .error((int code, String msg) -> {
                    Log.e("test", "待生产批号列表请求错误 " + code + " " + msg);
                    Toast.makeText(_mActivity, "待生产批号列表请求错误: " + msg, Toast.LENGTH_SHORT).show();
                })
                .build()
                .get();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshList(RefreshListEvent event) {
        if (event.getIndex() == 1) {
            curPage = 0;
            queryList(curPage, false);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
